package v1

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"jwgin/model/mysql"
	"jwgin/service"
)

type news struct{}

func (l *news) Routers(Router *gin.RouterGroup) {
	//文章列表
	Router.GET("news", l.get)         //列表
	Router.GET("news/:id", l.getById) //详情
}

func (l *news) get(c *gin.Context) {
	count, size, offset := pages(c)
	RoleID := c.GetUint("RoleID")
	if RoleID == 0 {
		RespErr(c, fmt.Errorf("系统用户认证失败"))
		return
	}

	db := service.G.Model(mysql.News{}).
		Joins("JOIN `news_class` ON news_class.id = news.news_class_id").
		Where("news.comid = ?", RoleID).Where("news.news_statu = 1")

	if classId := c.Query("classId"); classId != "" {
		db = db.Where("news_class_id = ?", classId)
	}

	//时间筛选
	startTime := c.Query("startTime")
	endTime := c.Query("endTime")
	if startTime != "" && endTime != "" {
		db = db.Where(" news.addtime > ? AND news.addtime < ? ", startTime, endTime)
	}

	list := []map[string]interface{}{}
	db.Select("class_name,news.*").Count(&count).Offset(offset).Limit(size).Order("id DESC").Scan(&list)
	RespList(c, count, list)
}
func (l *news) getById(c *gin.Context) {
	id := c.Param("id")
	if id == "" {
		RespErr(c, fmt.Errorf("参数错误"))
		return
	}
	RoleID := c.GetUint("RoleID")
	if RoleID == 0 {
		RespErr(c, fmt.Errorf("系统用户认证失败"))
		return
	}
	data := mysql.News{}
	service.G.
		Where("comid = ?", RoleID).Where("news_statu = 1 AND id = ? ", id).First(&data)
	RespSucc(c, data)
}
